package com.example.reggie.controller;

import com.example.reggie.common.deploy.R;
import com.example.reggie.common.table.MsgTable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    private String path ="D:\\img\\";
    @PostMapping("/upload")
    public R<String > upload(MultipartFile file){

        String originalFileName=file.getOriginalFilename();
        String suffix=originalFileName.substring(originalFileName.lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString()+suffix;
        try {
            File dir=new File(path);
            if(! dir.exists()){
                dir.mkdir();
            }
            file.transferTo(new File(path+newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newFileName);
    }

    @GetMapping("/download")
    public void download(String name , HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");
            //输入流读入
            FileInputStream fis=new FileInputStream(path+name);
            //输出流回写到页面
            ServletOutputStream outputStream = response.getOutputStream();
            int len;
            byte[] bytes=new byte[1024];
            while ((len=fis.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            fis.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
